import React, { lazy } from "react"
import { Navigate, RouteObject } from "react-router-dom"

import Login from "../pages/Login"
import Home from "../pages/Home"

import * as constant from "./constant"
import { getItem } from "./storage"

const load = (name:string):React.ReactElement=>{
  let Component = lazy(()=>import(`../pages/${name}`))
  console.log(`load ${name}...`);
  return <Component />
}

const ProtectedHome = ()=>{
  const token = getItem(constant.KEY_TOKEN)
  console.log("protectedHome...", token)
  return token ? <Home /> : <Navigate to="/login" replace={true} />
}

const Appraisal = ()=>{
  const token = getItem(constant.KEY_TOKEN)
  console.log("appraisal...", token);
  return token ? <Navigate to="/home" replace={true} /> : <Navigate to="/login" replace={true} />
}

const defaultRoutes:RouteObject[] = [
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/home/*",
    element: <ProtectedHome />,
    children: [],
  },
  {
    path: "*",
    element: <Appraisal />
  },
]

export {
  defaultRoutes,
  load 
}